<?php

/**
 * It is used to manage data of tips  table
 * 
 * @property int $tip_id primary key
 * @property int $user_id 
 * @property string $title 
 * @property string $text 
 * @property int $time_created
 */
class Tip extends CActiveRecord {

    const TOTAL_RECORD = 8;

    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{tips}}';
    }

    public function relations() {
	return array(
	    'user' => array(self::BELONGS_TO, 'User', 'user_id')
	);
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	return array(
	    array('title, text', 'required', 'on' => 'insert, update'),
	    array('tip_id, user_id', 'safe'),
	    array('title, text', 'safe', 'on' => 'search'),
	);
    }

    /**
     * search in frontend
     */
    public function search() {
	$criteria = new CDbCriteria();

	$criteria->compare('text', $this->text, TRUE);
	$criteria->compare('title', $this->title, TRUE);

	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	    'pagination' => array(
		'pageSize' => param('pageSize')
	    ),
	    'sort' => array(
		'defaultOrder' => array(
		    'tip_id' => CSort::SORT_DESC
		)
	    )
	));
    }

    public function afterSave() {
	parent::afterSave();
	_clearCache('aTips');
    }

    public function afterDelete() {
	parent::afterDelete();
	_clearCache('aTips');
    }

    /**
     * get all tips
     * 
     * @return array
     */
    public static function getListTips() {
	$aTips = Yii::app()->cache->get('aTips');
	if ($aTips === FALSE) {
	    $aTips = array();
	    $tips = db()->createCommand('SELECT * FROM {{tips}}')->queryAll();
	    if ($tips) {
		$aTips = $tips;
	    }
	    Yii::app()->cache->set('aTips', $aTips);
	}
	return $aTips;
    }

}
